/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import type {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
} from '@ant-design/pro-layout';
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useEffect, useState } from 'react';
import type { Dispatch } from 'umi';
import { Result, Button } from 'antd';
import { Link, useIntl, connect } from 'umi';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import type { ConnectState } from '@/models/connect';
import logo from '@/assets/gs_logo.png';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="您没有访问权限,请联系相关人员"
    extra={
      <Button type="primary">
        <Link to="/user/login">返 回 登 录</Link>
      </Button>
    }
  />
);

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: Record<string, MenuDataItem>;
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
  user: any;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: Record<string, MenuDataItem>;
};


const isPerm = (routerPerms: any, dataPerms: any) => {

  if (Object.prototype.toString.call(routerPerms) == '[object String]') {
    return dataPerms && dataPerms.length > 0 && dataPerms.indexOf(routerPerms) > -1;
  }
  if (Object.prototype.toString.call(routerPerms) == '[object Array]') {
    let returnVal = false;
    routerPerms.map((el: string) => {
      returnVal === false && (returnVal = dataPerms.indexOf(el) > -1);
    })
    return returnVal;
  }
  return false;
}

/**
 * use Authorized check all menu item
 */

const menuDataRender = (menuList: MenuDataItem[], perms: [] = []): MenuDataItem[] => {
  return menuList.map((item) => {
    const localItem = {
      ...item,
      children: item && item.children ? menuDataRender(item.children, perms) : [],
    };

    const authority = isPerm(item.perm, perms) || !item.perm ? null : item.perm;
    return Authorized.check(authority, localItem, null) as MenuDataItem;
  });
};

const defaultFooterDom = (
  <DefaultFooter
    copyright="上饶市劳动监察局 保留所有权利 (技术单位：上饶数金保科技有限公司)"
    links={[
      {
        key: 'BEIAN',
        title: '网站备案号: 赣ICP备2021003785号-2',
        href: 'https://beian.miit.gov.cn',
        blankTarget: true,
      },
    ]}
  />
);
const findPath = (menuList: MenuDataItem[], path: string) => {
  let item: any = null;
  menuList.map((el) => {
    if (item) {
      return;
    }
    if (el.path == path) {
      item = el;
      return;
    }
    item = el && el.children ? findPath(el.children, path) : null;
  });
  return item;
};

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    children,
    settings,
    user,
    location = {
      pathname: '/',
    },
  } = props;

  const [showTitle, setShowTitle] = useState<boolean>(true);

  const handleMenuCollapse = (payload: boolean): void => {
    // if (!payload) {
    //   setShowTitle(false);
    // }
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority
  const {
    currentUser: { perms = [''] },
  } = user;
  const curRoute = findPath(props.route.routes || [], location.pathname || '/') || {};
  const authorized = curRoute
    ? {
      authority:
        (curRoute.perm && (Array.isArray(curRoute.perm) ? curRoute.perm.some((item: any) => perms.indexOf(item) > -1) : (perms.indexOf(curRoute.perm) > -1))) || !curRoute.perm || perms.length < 1
          ? null
          : curRoute.perm,
    }
    : { authority: null };
  const { formatMessage } = useIntl();
  if (perms.length <= 0) {
    return noMatch;
  }

  return (
    <>
      <ProLayout
        locale="zh-CN"
        // logo={logo}
        formatMessage={formatMessage}
        menuHeaderRender={(logoDom, titleDom) => {
          return (
            <div style={{ width:'100%' }} >
              <img style={{ width:'100%',height:'60px' }} src={logo} alt="" />
            </div>
          );
        }}
        onCollapse={handleMenuCollapse}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || menuItemProps.children || !menuItemProps.path) {
            return defaultDom;
          }

          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        breadcrumbRender={false}
        footerRender={() => defaultFooterDom}
        menuDataRender={(menuList: MenuDataItem[]) => menuDataRender(menuList, perms)}
        rightContentRender={() => <RightContent showNotice={true} />}
        {...props}
        {...settings}
      >
        <Authorized authority={authorized!.authority} noMatch={noMatch}>
          {children}
        </Authorized>
      </ProLayout>
    </>
  );
};

export default connect(({ global, settings, user }: ConnectState) => ({
  settings,
  user,
}))(BasicLayout);
